package com.emm.yixun.website.controller.estate;
//框架包
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.common.model.BaseCodeValue;
//变化的引用
import com.emm.yixun.common.model.ProjectBuilding;
import com.emm.yixun.common.model.ProjectPremisesIndustData;
import com.emm.yixun.common.model.ProjectPremisesIndustDataVersion;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.ProjectBuildingDto;
import com.emm.yixun.common.model.dto.ProjectPremisesIndustDataDto;
import com.emm.yixun.common.model.dto.ProjectPremisesIndustDataVersionDto;
import com.emm.yixun.common.model.dto.RootClass;
import com.emm.yixun.common.model.enums.VersionEnum;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.estate.service.ProjectBuildingServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataVersionServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.estate.ProjectBudingVo;




@Controller
@RequestMapping("/estate/projectBuilding/")
public class ProjectBuildingController extends BaseController<ProjectBuilding>{
	
	@Autowired
	private ProjectBuildingServiceFacade projectBuildingServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private  ProjectPremisesIndustDataServiceFacade projectPremisesIndustDataServiceFacade;
	@Autowired
	private BaseCodeValueServiceFacade  baseCodeValueServiceFacade;
	@Autowired
	private ProjectPremisesIndustDataVersionServiceFacade premisesIndustDataVersionServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));		
			return "/estate/projectBuilding/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	//查看
	@RequestMapping(value="detail")
	@MerchantResourcesConfig(resourcesCode="menu_0003_0001_0016")
    public String detail(Long id, ModelMap map, HttpServletRequest request, HttpServletResponse servletResponse){
    	AjaxRes ar = getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:view"))){
        	try {
        		String url = "/estate/projectBuilding/detail";
        		map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
				Response<ProjectBuilding> response=projectBuildingServiceFacade.findById(id);
				if(response.isSuccess()){
					Map<String, String> projectMap = new HashMap<String, String>();
					projectMap = projectServiceFacade.projectLevelName(id, "3");
					map.addAttribute("manageObject", projectMap.get("manageObject"));
					map.addAttribute("parentName", projectMap.get("parentName"));
					ProjectBuilding build = response.getEntity();
					if("1".equals(build.getIsCarArea())){
						url = "/estate/projectCararea/detail_new";
					}
					ar.setSucceed(build);
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
				map.addAttribute("ar", ar);
				return url;
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
        return Const.NO_AUTHORIZED_URL;
    }
	
	//查看
	@RequestMapping(value="detailLC")
    public String detail(Long id, ModelMap map){
    	AjaxRes ar = getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:view"))){
        	try {
        		String url = "/estate/projectBuilding/detailLC";
        		map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
				Response<ProjectBuilding> response=projectBuildingServiceFacade.findById(id);
				if(response.isSuccess()){
					Map<String, String> projectMap = new HashMap<String, String>();
					projectMap = projectServiceFacade.projectLevelName(id, "3");
					map.addAttribute("manageObject", projectMap.get("manageObject"));
					map.addAttribute("parentName", projectMap.get("parentName"));
					ProjectBuilding build = response.getEntity();
					if("1".equals(build.getIsCarArea())){
						url = "/estate/projectCararea/detail_new";
					}
					ar.setSucceed(build);
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
				//业态数据
				ProjectPremisesIndustDataDto dataDto = new ProjectPremisesIndustDataDto();
				dataDto.setBuildingId(id);
				ResponseList<ProjectPremisesIndustData> datas = projectPremisesIndustDataServiceFacade.findByDto(dataDto);
				if(datas.isSuccess()&&datas.getEntity()!=null&&datas.getEntity().size()>0){
					ProjectPremisesIndustData indust = datas.getEntity().get(0);
					Response<BaseCodeValue> baseCode = baseCodeValueServiceFacade.findById(new Long(indust.getIndustMark()));
					if(baseCode.isSuccess()&&baseCode.getEntity()!=null){
						indust.setIndustMark(baseCode.getEntity().getCodeName());
					}
					map.addAttribute("industDatas",indust);
					
					//查询对应版本信息
					ProjectPremisesIndustDataVersionDto verDto = new ProjectPremisesIndustDataVersionDto();
					verDto.setIndustId(indust.getId());
					ResponseList<ProjectPremisesIndustDataVersion> versionList = premisesIndustDataVersionServiceFacade.findByDto(verDto);
				
					map.addAttribute("versionList", versionList.getEntity());
				}
				
				map.addAttribute("ar", ar);
				return url;
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
        return Const.NO_AUTHORIZED_URL;
    }
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(ProjectBuildingDto dto){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setDelFlag("0");
        		dto.setUpdateUserId(user.getId());
        		dto.setUpdateTime(new Date());
				Response<ProjectBuildingDto> response=projectBuildingServiceFacade.save(dto);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
		AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:view"))){
        	try {
				Response<ProjectBuilding> response=projectBuildingServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//查看
	@RequestMapping(value="viewLC", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes viewLC(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:view"))){
        	try {
				Response<ProjectBuilding> response=projectBuildingServiceFacade.findById(id);
				ProjectBudingVo vo = new ProjectBudingVo();
				if(response.isSuccess()){
					ProjectBuilding building = response.getEntity();
					BeanUtil.convert2T(vo, building);
					//查询楼栋的业态数据
					ProjectPremisesIndustDataDto industData = new ProjectPremisesIndustDataDto();
					industData.setBuildingId(id);
					ResponseList<ProjectPremisesIndustData> responseList = projectPremisesIndustDataServiceFacade.findByDto(industData);
					if(responseList.isSuccess()&&responseList.getEntity()!=null&&responseList.getEntity().size()>0){
						ProjectPremisesIndustData indust = responseList.getEntity().get(0);
						vo.setInfo(indust);
						ProjectPremisesIndustDataVersionDto versionQuery = new ProjectPremisesIndustDataVersionDto();
						versionQuery.setIndustId(indust.getId());
						ResponseList<ProjectPremisesIndustDataVersion> vesList = premisesIndustDataVersionServiceFacade.findByDto(versionQuery);
						if(vesList.isSuccess()&&vesList.getEntity()!=null&&vesList.getEntity().size()>0){
							List<ProjectPremisesIndustDataVersion> array = vesList.getEntity();
							for (ProjectPremisesIndustDataVersion obj:array) {
								obj.setVersionVal(VersionEnum.getByDescription(obj.getVersionName()).getCode()+"");
							}
						}
						vo.setVersions(vesList.getEntity());
						// 根据小业态找到大业态
						Response<BaseCodeValue> baseCode = baseCodeValueServiceFacade.findById(new Long(indust.getIndustMark()));
						vo.setTypeId(baseCode.getEntity().getTypeId());
					}
					//业态对应的版本数据
					ar.setSucceed(vo);
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(ProjectBuildingDto dto, HttpServletRequest request,ProjectPremisesIndustDataDto premisesIndustDataDto){
		AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:edit"))){
        	try {
        		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        		String deliveryDateOrigin = request.getParameter("deliveryDateOrigin");
        		String salesPermissionDateOrigin = request.getParameter("salesPermissionDateOrigin");
        		String openTimeOrigin = request.getParameter("openTimeOrigin");
        		if(StringUtils.isNotEmpty(deliveryDateOrigin)){
        			dto.setDeliveryDate(sdf.parse(deliveryDateOrigin));
        		}
        		if(StringUtils.isNotEmpty(salesPermissionDateOrigin)){
        			dto.setSalesPermissionDate(sdf.parse(salesPermissionDateOrigin));
        		}
        		if(StringUtils.isNotEmpty(openTimeOrigin)){
        			dto.setOpenTime(sdf.parse(openTimeOrigin));
        		}
        		Response<Integer> response = projectBuildingServiceFacade.updateByPrimaryKey(dto, true);
        		if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="editLC", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes editLC(ProjectBuildingDto dto, HttpServletRequest request,ProjectPremisesIndustDataDto premisesIndustDataDto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:edit"))){
        	try {
        		if(premisesIndustDataDto.getVersionDate()!=null&&premisesIndustDataDto.getVersionDate().size()>0){
        			if(!vaildList(premisesIndustDataDto.getVersionDate())){
            			ar.setSucceedMsg("生效时间不能重复!");
            			return ar;
            		}
        		}
        		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        		String deliveryDateOrigin = request.getParameter("deliveryDateOrigin");
        		String salesPermissionDateOrigin = request.getParameter("salesPermissionDateOrigin");
        		String openTimeOrigin = request.getParameter("openTimeOrigin");
        		if(StringUtils.isNotEmpty(deliveryDateOrigin)){
        			dto.setDeliveryDate(sdf.parse(deliveryDateOrigin));
        		}
        		if(StringUtils.isNotEmpty(salesPermissionDateOrigin)){
        			dto.setSalesPermissionDate(sdf.parse(salesPermissionDateOrigin));
        		}
        		if(StringUtils.isNotEmpty(openTimeOrigin)){
        			dto.setOpenTime(sdf.parse(openTimeOrigin));
        		}
        		Response<Integer> response = projectBuildingServiceFacade.updateByPrimaryKey(dto, true);
        		//PMO 二期修改，操作楼栋业态数据
        		//premisesIndustDataService.industDataSave(premisesIndustDataDto, dto.getId());
        		if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	
	public Boolean vaildList(List<String> list){
		String temp = "";
		for (int i = 0; i < list.size() - 1; i++) {
			temp = list.get(i);
			for (int j = i + 1; j < list.size(); j++) {
				if(temp!=null&&temp!=""&&temp.length()>0){
					if (temp.equals(list.get(j))) {
						return false;
					}
				}else{
					continue;
				}
			}
		}
		return true;
	}
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:delete"))){
        	try {
        		Response<Integer> response=projectBuildingServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(ProjectBuildingDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectBuilding:list"))){
        	try {
        		Page<ProjectBuilding> response=projectBuildingServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<ProjectBuilding>());
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	@RequestMapping(value = "findBuildingList")
	public @ResponseBody
	RootClass findBuildingList(ProjectBuildingDto dto) {
		User user = ShiroUtil.getCurrentUser();
		dto.setDelFlag("0");
		dto.setMerchantId(user.getMerchantId());
		ResponseList<ProjectBuilding> buildingList = projectBuildingServiceFacade.findByDto(dto);
		RootClass root = new RootClass();
		root.setRoot(buildingList.getEntity());
		return root;
	}
}
